package refresolver

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"fmt"
	"reflect"

	k8gbv1beta1 "github.com/k8gb-io/k8gb/api/v1beta1"
	"github.com/k8gb-io/k8gb/controllers/refresolver/gatewayapigrpcroute"
	"github.com/k8gb-io/k8gb/controllers/refresolver/gatewayapihttproute"
	"github.com/k8gb-io/k8gb/controllers/refresolver/ingress"
	"github.com/k8gb-io/k8gb/controllers/refresolver/istiovirtualservice"
	"github.com/k8gb-io/k8gb/controllers/refresolver/lbservice"
	"github.com/k8gb-io/k8gb/controllers/utils"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

// GslbReferenceResolver resolves references to other kubernetes resources concerning ingress configuration
type GslbReferenceResolver interface {
	// GetServers retrieves GSLB the server configuration
	GetServers() ([]*k8gbv1beta1.Server, error)
	// GetGslbExposedIPs retrieves the load balancer IP address of the GSLB
	GetGslbExposedIPs(gslbAnnotations map[string]string, parentZoneDNSServers utils.DNSList) ([]string, error)
}

// New creates a new GSLBReferenceResolver
func New(gslb *k8gbv1beta1.Gslb, k8sClient client.Client) (GslbReferenceResolver, error) {
	if reflect.DeepEqual(gslb.Spec.ResourceRef, k8gbv1beta1.ResourceRef{}) {
		return ingress.NewEmbeddedResolver(gslb, k8sClient)
	}
	if gslb.Spec.ResourceRef.Kind == "Ingress" && gslb.Spec.ResourceRef.APIVersion == "networking.k8s.io/v1" {
		return ingress.NewReferenceResolver(gslb, k8sClient)
	}
	if gslb.Spec.ResourceRef.Kind == "VirtualService" {
		if gslb.Spec.ResourceRef.APIVersion == "networking.istio.io/v1beta1" ||
			gslb.Spec.ResourceRef.APIVersion == "networking.istio.io/v1" {
			return istiovirtualservice.NewReferenceResolver(gslb, k8sClient)
		}
	}
	if gslb.Spec.ResourceRef.Kind == "Service" && gslb.Spec.ResourceRef.APIVersion == "v1" {
		return lbservice.NewReferenceResolver(gslb, k8sClient)
	}
	if gslb.Spec.ResourceRef.Kind == "HTTPRoute" && gslb.Spec.ResourceRef.APIVersion == "gateway.networking.k8s.io/v1" {
		return gatewayapihttproute.NewReferenceResolver(gslb, k8sClient)
	}
	if gslb.Spec.ResourceRef.Kind == "GRPCRoute" && gslb.Spec.ResourceRef.APIVersion == "gateway.networking.k8s.io/v1" {
		return gatewayapigrpcroute.NewReferenceResolver(gslb, k8sClient)
	}
	return nil, fmt.Errorf("APIVersion:%s, Kind:%s not supported", gslb.Spec.ResourceRef.APIVersion, gslb.Spec.ResourceRef.Kind)
}
